package com.czc.pay.controllers;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.utils.ConfigReader;
import com.jzoom.zoom.common.Destroyable;
import com.jzoom.zoom.common.utils.MapUtils;
import com.jzoom.zoom.http.Http;
import com.jzoom.zoom.http.Http.Client;
import com.jzoom.zoom.http.Http.HttpCallback;
import com.jzoom.zoom.http.Http.Response;

public class ShiminModel implements Destroyable,  HttpCallback {
	
private static final Log log = LogFactory.getLog(ShiminModel.class);
	
	private String baseUrl;
	
	private String ip;
	
	private String clientId;
	
	private String password;
	
	private Client client;

	/**
	 * 
	 * @author jzoom
	 *
	 */
	public static final class ShiminUserInfo{
		
	}
	
	public ShiminModel() {
		baseUrl = "http://218.5.69.218:9088";
		ip = "120.79.190.42";
		clientId = "ecard";
		password = "E_2018_card";
		
		client = Http.newClient()
				.setReadTimeout(10000).setConnectTimeout(10000)
				.addDefaultHeader("X-Forward-For".toLowerCase(), ip)
				.addDefaultHeader( Http.Content_Type , Http.APPLICATION_JSON)
				.setBaseUrl(baseUrl).setCallback(this);
	}
	
	
	@Override
	public void destroy() {
		
	}
	
	public Map<String, Object> getUserInfo(String token) throws IOException {
		Response response = client.postJson( "/user/query-token/full", MapUtils.asMap("token",token));
		return response.jsonMap();
	}
	
	public Map<String, Object> cardList(String userName, String cardId) throws IOException {
		Response response = client.postJson( "/card/member-card-list/02", MapUtils.asMap("userName", userName, "cardId", cardId));
		return response.jsonMap();
	}


	@Override
	public void preHandle(HttpURLConnection connection) throws IOException {
		
		String timestamp = String.valueOf(System.currentTimeMillis());
		String src = String.format("%s:%s:%s", clientId,timestamp ,DigestUtils.md5Hex(password));
		String signature = DigestUtils.md5Hex(src);
		log.info("待签名:" +  src + " 密码:" + password + " 签名结果:"+signature + " header:" + connection.getRequestProperty(Http.X_Forward_For) );
		
		connection.addRequestProperty("Authorization", 
				String.format("UMS01 %s:%s:%s", 
						clientId,
						timestamp,
						signature ));
	}

	@Override
	public Response afterHandle(HttpURLConnection connection, Response response) throws IOException {

		return response;
	}


}
